<?php

namespace app\bll;

use app\validate\HomeMenuCate as ValidateHomeMenuCate;
use Exception;
use support\Db;
use Throwable;

/**
 * 前台菜单分类
 */
class HomeMenuCate
{
    /**
     * 获取分类
     *
     * @return array
     */
    public function select(int $siteid): array
    {
        return  Db::table('frame_home_menu_cate')
            ->where('siteid', '=', $siteid)
            ->get()
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }

    /**
     * 分类详情
     *
     * @param integer $id
     * @return array
     */
    public function find(int $id, int $siteid): array
    {
        $data =  Db::table('frame_home_menu_cate')
            ->where('id', '=', $id)
            ->where('siteid', '=', $siteid)
            ->first();
        return $data === null ? [] : get_object_vars($data);
    }

    /**
     * 添加分类
     *
     * @param array $data
     * @return integer
     */
    public function add(array $data): int
    {
        $validateHomeMenuCate = new ValidateHomeMenuCate();
        if (!$validateHomeMenuCate->check($data)) {
            throw new Exception($validateHomeMenuCate->getSimpleError());
        }

        return Db::table('frame_home_menu_cate')
            ->insertGetId($data);
    }


    /**
     * 编辑
     *
     * @param integer $id
     * @param array $data
     * @return integer
     */
    public function edit(int $id, int $siteid, array $data): int
    {

        $validateHomeMenuCate = new ValidateHomeMenuCate();
        if (!$validateHomeMenuCate->check($data)) {
            throw new Exception($validateHomeMenuCate->getSimpleError());
        }

        return Db::table('frame_home_menu_cate')
            ->where('id', '=', $id)
            ->where('siteid', '=', $siteid)
            ->update($data);
    }

    /**
     * 删除分类
     *
     * @param integer $id
     * @param integer $siteid
     * @return void
     */
    public function delete(int $id, int $siteid)
    {

        Db::beginTransaction();

        try {
            Db::table('frame_home_menu_cate')
                ->where('id', '=', $id)
                ->where('siteid', '=', $siteid)
                ->delete();
            Db::table('frame_home_menu')
                ->where('cid', '=', $id)
                ->where('siteid', '=', $siteid)
                ->delete();
            Db::commit();
        } catch (Throwable $ex) {
            Db::rollBack();
            throw $ex;
        }
    }
}
